import { useEffect, useState } from 'react'
import {
  Button,
  Form,
  Table,
  Input,
  Pagination,
  Popconfirm,
  message,
  Select,
  Switch,
  Modal
} from 'antd';
import style from '../../assets/scss/news/news.module.scss'
import { Newslist, Cationlist, NewsAdd, NewsDeleteall, NewsDelete, Newsget } from '../../apis/News/news'
import { NewstDta, CationDta, } from '../../apis/News/newstype';
import { useNavigate } from "react-router-dom";




const News = (): JSX.Element => {
  // 表头
  const columns: any = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },

    {
      title: '类型',
      dataIndex: 'typename',
      key: 'typename',
      render: (text: string, record: any) => <div>
        <Button onClick={showModal(record.id)} type="link">{text}</Button>
      </div>,
    },

    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 160,
    },

    {
      title: '图片',
      dataIndex: 'picture',
      key: 'picture',
      render: (picture: any,) => <div >
        <img className={style.img} src={process.env.REACT_APP_IMG_URL + picture} />
      </div>
    },

    {
      title: '状态',
      dataIndex: 'state',
      key: 'id',
      render: (text: any, record: any,) => <div >
        <Switch defaultChecked={text} onChange={onSwitch(record)} />
      </div>
      ,
    },

    {
      title: '发布时间',
      dataIndex: 'addtime',
      key: 'addtime',
    },

    {
      title: '发布人',
      dataIndex: 'edituser',
      key: 'edituser',
      // width: 160,
    },

    {
      title: '操作',
      key: 'id',
      width: 160,
      render: (record: any,) => <div className={style.Button}>
        <Button className={style.Edit} type="link" onClick={NewsEdit(record)}>
          编辑
        </Button>
        <Popconfirm title="请确认是否删除？？"
          okText="确定"
          cancelText="取消"
          onConfirm={NewsDell(record.id)}>
          <Button type="primary" danger>删除</Button>
        </Popconfirm>

      </div>
      ,
    },
  ];

  // 表单
  const [loginform] = Form.useForm();

  // 路由跳转
  const navigate = useNavigate()

  // 表格选中的数组
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);


  // 获取表格选中的数据
  const onRoomChange = (houseno: React.Key[]) => {
    setSelectedRowKeys(houseno);
  };

  const NesSelection = { selectedRowKeys, onChange: onRoomChange, };



  // 公告列表参数
  let column: NewstDta = {
    key: '',
    type: 0,
    page: 1,
    psize: 5
  }

  // 公告列表数组
  const [lsit, lists] = useState([])

  // 公告分类参数
  const row: CationDta = {
    page: 1,
    psize: 3
  }

  // 公告分类数组
  const [Catilsit, CatilsitEit] = useState([])

  // 页面总条数
  const [total, totaleit] = useState(0)

  // 请求公告列表
  const GetNewslist = async () => {
    const res: any = await Newslist(column)
    console.log(res);
    if (res.errCode === 10000) {
      lists(res.data.list)
      totaleit(res.data.counts)
    }
  }

  // 分页
  const onPageChange = async (current: number, size: number) => {
    console.log(current, size);
    column = { ...column, page: current, psize: size }
    GetNewslist()
  }

  // Switch开关
  // Switch开关
  const onSwitch = (checked: any) => {
    return async () => {
      if (checked.state === 1) {
        checked.state = 0
      } else {
        checked.state = 1
      }
      const res: any = await NewsAdd(checked)
      console.log(checked);
      console.log(res);
      if (res.errCode === 10000) {
        message.open({
          type: 'success',
          content: '状态更新成功',
        });
        // GetNewslist()
      }
    }
  };

  //  请求公告分类
  const GetNoticetypelist = async () => {
    const res: any = await Cationlist(row)
    console.log(res);
    if (res.errCode === 10000) {
      CatilsitEit(res.data.list)
      console.log(Catilsit);
    }
  }

  // 搜索
  const onFinish = (values: any,) => {
    console.log(values);
    column = { ...column, ...values, page: 1, }
    GetNewslist()
  };

  // 点击添加
  const NewsMngadd = () => {
    navigate('/home/NewsOperate')
  }

  // 编辑
  const NewsEdit = (e: any) => {
    return () => {
      console.log(1111);
      console.log(e);
      navigate(`/home/NewsOperate?id=` + e.id)
    }
  }

  // 批量删除 
  const Deleteall = async () => {
    const res: any = await NewsDeleteall({ ids: selectedRowKeys })
    console.log(res);
    if (res.errCode === 10000) {
      message.open({
        type: 'success',
        content: '删除成功',
      });
      GetNewslist()
    }
  }


  // 删除
  const NewsDell = (e: any) => {
    return async () => {
      const res: any = await NewsDelete({ id: e })
      console.log(res);
      if (res.errCode === 10000) {
        message.open({
          type: 'success',
          content: '删除成功',
        });
        GetNewslist()
      }
    }
  }

  let loading=false
  //  批量删除 是否禁用
  const hasSelected = selectedRowKeys.length > 0;

  // 对话框是否显示
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 详情
  const [Separate, setSeparate]: any = useState({});

  // 点击当前行数据  根据id获取网络请求
  const showModal = (e: number) => {
    return async () => {
      console.log(e);
      const res: any = await Newsget({ id: e })
      console.log(res);
      if (res.errCode === 10000) {
        setSeparate(res.data)
      }
      setIsModalOpen(true);
    }
  };

  // 确认
  const handleOk = () => {
    setIsModalOpen(false);
  };

  // 关闭对话框
  const handleCancel = () => {
    setIsModalOpen(false);
  };


  useEffect(() => {
    // 请求公告列表
    GetNewslist()
    // 请求公告分类
    GetNoticetypelist()
  }, [])

  return (
    <div>
      <div className={style.News}>
        <div className={style.Newstext}>
          <span>公告列表</span>
        </div>
        <div className={style.NewsSearch}>
          <Form className={style.NewsFrom} form={loginform} onFinish={onFinish}>
            <Form.Item label="新闻" className={style.Item} name='key'>
              <Input placeholder='新闻名' />
            </Form.Item>

            <Form.Item className={style.Selects} label="公告类型" name='type'>
              <Select placeholder="请选择" >
                {
                  Catilsit.map((item: any) => (
                    <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                  )
                  )
                }
              </Select>
            </Form.Item>

            <Form.Item className={style.earcwh}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div className={style.Add}>
          <Button type="primary" htmlType="submit" onClick={NewsMngadd}>
            添加
          </Button>
          <Popconfirm
            title="请确认是否删除？？"
            okText="确定"
            cancelText="取消"
            onConfirm={Deleteall}
          >
            <Button type="primary" danger disabled={!hasSelected} loading={loading}>
              批量删除
            </Button>
          </Popconfirm>
        </div>


        {/* 表格 */}
        <Table
          rowSelection={{
            type: 'checkbox',
            ...NesSelection,
          }}
          rowKey={(record: any) => record.id}
          className={style.Table}
          pagination={false}
          dataSource={lsit}
          columns={columns} >
        </Table>

        <Pagination
          className={style.Pagination}
          total={total}
          showTotal={(total) => `总条数 ${total} 条`}
          showQuickJumper
          showSizeChanger
          // hideOnSinglePage={true}
          defaultPageSize={column.psize}
          defaultCurrent={column.page}
          onChange={onPageChange}
        ></Pagination>


        <Modal title="公告详情" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <div className={style.Modal}>
            <div>添加时间：{Separate.addtime}</div>
            <div>
              <img className={style.img} style={{ width: "4rem", height: "3rem" }} src={process.env.REACT_APP_IMG_URL + Separate.picture} />
            </div>
          </div>
        </Modal>
      </div>
    </div>
  )
}
export default News